package com.woniuxy.oa.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.woniuxy.oa.entity.Approval;
import com.woniuxy.oa.entity.Employee;
import com.woniuxy.oa.entity.Holiday;
import com.woniuxy.oa.entity.Reimbursement;
import com.woniuxy.oa.enums.ApprovalApplyType;
import com.woniuxy.oa.exception.HolidayException;
import com.woniuxy.oa.exception.ReimbursementException;
import com.woniuxy.oa.service.ReimbursementService;
import com.woniuxy.oa.utils.ApprovalUtil;

@Controller
@RequestMapping("/reimbursement")
public class ReimbursementController {

	@Autowired
	private ReimbursementService reimbursementService;

	public void setReimbursementService(ReimbursementService reimbursementService) {
		this.reimbursementService = reimbursementService;
	}

	// 修改方法
	@Transactional(rollbackFor = { RuntimeException.class, Error.class, Exception.class })
	@ResponseBody
	@RequestMapping("/modifyReimbursement")
	public List<String> modifyReimbursement(Approval approval, Reimbursement reimbursement,
			HttpServletRequest request) {
		List<String> msg = new ArrayList<String>();
		System.out.println("修改方法被访问");
		System.out.println("修改方法被访问" + approval);
		System.out.println("修改方法被访问" + reimbursement);
		try {
			// 非空验证
			if (approval == null || approval.getA_eid() == null || reimbursement == null
					|| reimbursement.getRb_id() == null || reimbursement.getRb_name() == null
					|| reimbursement.getRb_price() == null || reimbursement.getRb_company() == null) {
				msg.add("参数不能为空！");
				throw new ReimbursementException();
			}
			// 检查发过来的reimbursement是否是已存在的，不存在直接抛异常
			Reimbursement selectReimbursement = reimbursementService
					.selectReimbursementByRbid(reimbursement.getRb_id());
			if (selectReimbursement == null) {
				msg.add("该报销不存在");
				throw new ReimbursementException();
			}
			// 检查发过来的信息是否和查出来的信息一致
//				if(checkModifyInfo(approval,reimbursement,selectReimbursement)) {
//					msg.add("信息一致，不需要修改");
//					throw new HolidayException("信息一致，不需要修改");
//				}
			// 检查金额，单位默认为元
			if (!isMoneyNum(reimbursement.getRb_price())) {
				msg.add("金额不正确");
				throw new ReimbursementException();
			}

			Employee emp = (Employee) request.getSession().getAttribute("user");

			// 检查发过来的holiday对应的发起人是否为当前用户
//				if((holidayService.selectApprovalByAid(selectHoliday.getA_id()).getE_id())!=(emp.getId())) {
//					throw new HolidayException("操作用户不正确");
//				}

			// 修改报销信息
			reimbursementService.updateHoliday(reimbursement, selectReimbursement.getRb_id());
			// 修改审批关系
			reimbursementService.updateApprovalAeid(approval.getA_eid(), reimbursement.getA_id());
			msg.add("修改成功");
			return msg;
		} catch (Exception e) {
			e.printStackTrace();
//				msg.add("修改失败");
			return msg;
		}
	}

	private boolean isMoneyNum(Double rb_price) {
		Pattern pattern=Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
        Matcher match=pattern.matcher(rb_price.toString());
        return match.matches(); 

	}

	// 检查修改报销信息的方法
//	private boolean checkModifyInfo(Approval approval, Reimbursement reimbursement, Reimbursement selectReimbursement) {
//			boolean isOk= false;
//			Integer a_eid = approval.getA_eid();
//			if() {
//				
//				
//				isOk=true;
//			}
//			return isOk;
//		}

	// 删除方法,实际是把flag改为1
	@ResponseBody
	@RequestMapping("/deleteReimbursement")
	public List<String> deleteReimbursement(HttpServletRequest request) {
		List<String> msg = new ArrayList<String>();
		try {
			// 检查该审批申请中的发起人是否是当前用户
			Employee emp = (Employee) request.getSession().getAttribute("user");
			// 获取发过来的a_id
			Integer a_id = Integer.parseInt(request.getParameter("a_id"));
			// 根据审批号查到发起人id
			Integer e_id = reimbursementService.getIdByAid(a_id);
			System.out.println("收到的a_id为：" + a_id);
			// 这里先去掉，以后有user了就加上
//			if(emp.getId()==a_id) {
			reimbursementService.deleteReimbursementByAid(a_id);
//			}
			msg.add("删除成功");
			return msg;
		} catch (Exception e) {
			e.printStackTrace();
			msg.add("删除失败");
			return msg;
		}
	}

	// 创建报销申请的方法
	@Transactional(rollbackFor = { RuntimeException.class, Error.class, Exception.class })
	@RequestMapping("/createReimbursement")
	public String createReimbursementApply(Model model, HttpServletRequest request, Reimbursement reimbursement) {
		try {
			// 非空检查
			if (reimbursement.getRb_name() == null || reimbursement.getRb_price() == null
					|| reimbursement.getRb_company() == null) {
				throw new ReimbursementException("参数不能为空");
			}

			// 检查报销信息格式（单价格式验证）
			if (!isMoneyNum(reimbursement.getRb_price())) {
				
				throw new HolidayException("金额不正确");
			}
			
			// 向审批表插入一条信息，得到审批号
			Integer a_eid = Integer.parseInt(request.getParameter("a_eid"));
			;
			Integer a_id = ApprovalUtil.addApprovalGetId(request, a_eid, ApprovalApplyType.EXPEND);
			// 向报销表插入信息，并获得主键
			Integer rb_id = reimbursementService.addReimbursementGetId(a_id, reimbursement);
			if (rb_id > 0) {
				return "redirect:/apply.html";
			}
			throw new ReimbursementException("创建报销申请失败");
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", e.getMessage());
			return "redirect:/error.html";
		}
	}
}
